﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
using System.ServiceModel.Syndication;
using Microsoft.Phone.Tasks;
using NBA_Feed.BaseClass;

namespace NBA_Feed
{
    public partial class FeedListPage : PhoneApplicationPage
    {
        public FeedListPage()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Handles the SelectionChanged event of the feedListBox control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Controls.SelectionChangedEventArgs"/> instance containing the event data.</param>
        private void feedListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox listBox = sender as ListBox;

            if (listBox != null && listBox.SelectedItem != null)
            {
                // Get the SyndicationItem that was tapped.
                SyndicationItem sItem = (SyndicationItem)listBox.SelectedItem;

                // Set up the page navigation only if a link actually exists in the feed item.
                if (sItem.Links.Count > 0)
                {
                    // Get the associated URI of the feed item.
                    Uri uri = sItem.Links.FirstOrDefault().Uri;

                    // Create a new WebBrowserTask Launcher to navigate to the feed item. 
                    // An alternative solution would be to use a WebBrowser control, but WebBrowserTask is simpler to use. 
                    WebBrowserTask webBrowserTask = new WebBrowserTask();
                    webBrowserTask.Uri = uri;
                    webBrowserTask.Show();
                }
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.ApplicationTitle.Text = App.Title;
            refreshData();
            base.OnNavigatedTo(e);
        }

        private void refreshData()
        {
            _waiting.Visibility = System.Windows.Visibility.Visible;
            HttpLogic httpLogic = new HttpLogic();
            httpLogic.GetRssFeed(App.Url, (feed) =>
            {
                feedListBox.ItemsSource = feed.Items;

                _waiting.Visibility = System.Windows.Visibility.Collapsed;
            });
        }
    }
}
